package com.zxkj.commonpatrol.ui;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.czy.basecommon.utils.base.StateData;
import com.czy.basecommon.utils.tools.ActivityTool;
import com.czy.basecommon.utils.tools.TimeUtil;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.widget.OptionsPickerView;
import com.xuexiang.xui.widget.picker.widget.TimePickerView;
import com.xuexiang.xui.widget.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui.widget.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui.widget.picker.widget.listener.OnOptionsSelectListener;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectChangeListener;
import com.xuexiang.xui.widget.picker.widget.listener.OnTimeSelectListener;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.adapt.AddDeciveCustomViewAdapt;
import com.zxkj.commonpatrol.adapt.QuestListAdapt;
import com.zxkj.commonpatrol.databinding.ActivityAddDecive1Binding;
import com.zxkj.commonpatrol.databinding.ActivityAddDeciveBinding;
import com.zxkj.commonpatrol.model.response.DevTypeExtendInfo;
import com.zxkj.commonpatrol.model.response.DeviceType;
import com.zxkj.commonpatrol.model.response.PointInspectDeviceResponse;
import com.zxkj.commonpatrol.viewmodel.AddDeciveViewModel;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AddDeciveActivity1 extends BaseVmDataBindingActivity<ActivityAddDecive1Binding, AddDeciveViewModel> {
    //查看和编辑 复用
    private int type = 0;//0  查看,1 編輯
    private QuestListAdapt adapt;
    private TimePickerView mTimePicker;
    private int mDeciveTypeOption;
    private OptionsPickerView<Object> mDeciveType;
    private OptionsPickerView<Object> mType;
    private int mTypeOption;
    private OptionsPickerView<Object> mQuestType;
    private int mQuestTypeOption;
    private String RouteInspectNo;
    private String PointNo;
    private String DeviceNo;
    public int IsAdd;//是否新增（1：新增  0：编辑）
    private MiniLoadingDialog loadingDialog;
    private HashMap<String, String> hashMapTypeListDatas;
    private HashMap<Object, Object> hashTypeListDatas;

    private String Code1;
    private String Code2;
    private String Code3;
    private String Code4;
    private String DevTypeNo;
    private String QuestsNo;
    private HashMap<String,  List<DevTypeExtendInfo.Questions.QuestionItem>> hashMapQuestTypeDatas;
    private String RSName;
    private HashMap<String, String> hashMapQuestTypeDatas1;
    private AddDeciveCustomViewAdapt addDeciveCustomViewAdapt;
    private Map<String, String> values;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_add_decive1;
    }

    @Override
    public int initVariableId() {
        return BR.AddDeciveViewModel;
    }


    @Override
    protected void initUI() {
        if (getIntent().hasExtra("IsEdit")) {
            type = getIntent().getIntExtra("IsEdit", 0);
        }
        if (getIntent().hasExtra("RouteInspectNo")) {
            RouteInspectNo = getIntent().getStringExtra("RouteInspectNo");
        }
        if (getIntent().hasExtra("PointNo")) {
            PointNo = getIntent().getStringExtra("PointNo");
        }
        if (getIntent().hasExtra("DeviceNo")) {
            DeviceNo = getIntent().getStringExtra("DeviceNo");
        }
        if (getIntent().hasExtra("RSName")) {
            RSName = getIntent().getStringExtra("RSName");
        }
        viewModel.RSName.set(RSName);

        EditText a[] = {binding.edPointNb,binding.edPointQuestList, binding.edPointType};
        EditText b[] = {binding.edPointNb,
                binding.edPointCnName,
                binding.edPointEnName,
                binding.edPointCnLocation

        };
        if (type == 0) {
            IsAdd=0;
            //查看
            binding.tvTitle.setText("查看裝置");
            binding.btnNo.setVisibility(View.VISIBLE);
            setCheckFalse(a);
        } else {
            IsAdd=1;
            binding.btnNo.setVisibility(View.VISIBLE);
            //編輯
            binding.tvTitle.setText("新增裝置");
            setCheckTrue(b);

        }

        binding.recyList.setLayoutManager(new LinearLayoutManager(this));
        binding.recyAddView.setLayoutManager(new LinearLayoutManager(this));
    }


    @Override
    protected void setListener() {
        super.setListener();

        binding.edPointQuestList.setOnClickListener(v->{
            if (mQuestType!=null){
                mQuestType.show();
            }
        });
        binding.edPointType.setOnClickListener(v -> {
            if (mDeciveType != null) {
                mDeciveType.show();
            }
        });
        binding.btnNo.setOnClickListener(v->{
            if (loadingDialog == null) {
                loadingDialog = new MiniLoadingDialog(this, "加載中...");
            }
            loadingDialog.show();

            if (addDeciveCustomViewAdapt!=null){
               values = addDeciveCustomViewAdapt.Values;
            }else{
                values=null;
            }
            viewModel.Save(DevTypeNo,QuestsNo,values,PointNo,RouteInspectNo,IsAdd);
        });
        binding.qkBack.setOnClickListener(v->{
            ActivityTool.getInstance().popOneActivity(this);
        });
    }

    @Override
    protected void initData() {

        if (type == 0) {
            //查看
            if (loadingDialog == null) {
                loadingDialog = new MiniLoadingDialog(this, "加載中...");
            }
            loadingDialog.show();

            viewModel.ShowDetail(RouteInspectNo, PointNo, DeviceNo);
        } else {
            if (loadingDialog == null) {
                loadingDialog = new MiniLoadingDialog(this, "加載中...");
            }
            loadingDialog.show();
            viewModel.getDeviceType(PointNo);
        }
    }

    public void setCheckFalse(EditText... editTexts) {
        for (EditText editText : editTexts) {
            editText.setFocusable(false);
            editText.setEnabled(false);
            editText.setFocusableInTouchMode(false);
        }
    }

    public void setCheckTrue(EditText... editTexts) {
        for (EditText editText : editTexts) {
            editText.setFocusable(true);
            editText.setEnabled(true);
            editText.setFocusableInTouchMode(true);
        }
    }


    @Override
    protected void dataObserver() {
        super.dataObserver();


                viewModel.DevTypeCode.observe(this, new Observer<StateData<String>>() {
                    @Override
                    public void onChanged(StateData<String> stringStateData) {
                        DevTypeNo=stringStateData.getData();
                    }
                });
        viewModel.QuestsNo.observe(this, new Observer<StateData<String>>() {
            @Override
            public void onChanged(StateData<String> stringStateData) {
              QuestsNo=stringStateData.getData();
            }
        });
        viewModel.ZLListData.observe(this, new Observer<StateData<List<String>>>() {
            @Override
            public void onChanged(StateData<List<String>> listStateData) {
//                int size4 = listStateData.getData().size();
//                String[] array4 = (String[]) listStateData.getData().toArray(new String[size4]);
//                Type(array4);
            }
        });

        viewModel.Codes.observe(this, new Observer<StateData<List<String>>>() {
            @Override
            public void onChanged(StateData<List<String>> listStateData) {
                if (listStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    for (int i = 0; i < listStateData.getData().size(); i++) {
                        if (i==0){
                           Code1=listStateData.getData().get(i);
                        }
                        if (i==1){
                            Code2=listStateData.getData().get(i);
                        }
                        if (i==2){
                            Code3=listStateData.getData().get(i);
                        }
                        if (i==3){
                            Code4=listStateData.getData().get(i);
                        }
                    }
                }
            }
        });

        viewModel.ShowDatas.observe(this, new Observer<StateData<PointInspectDeviceResponse>>() {
            @Override
            public void onChanged(StateData<PointInspectDeviceResponse> pointInspectDeviceResponseStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (pointInspectDeviceResponseStateData.getStatus() == StateData.DataStatus.SUCCESS) {
                    if (pointInspectDeviceResponseStateData.getData().getDevPropertys() != null && pointInspectDeviceResponseStateData.getData().getDevPropertys().size() > 0) {
                         addDeciveCustomViewAdapt =new AddDeciveCustomViewAdapt(R.layout.item_add_decive_custom_view,pointInspectDeviceResponseStateData.getData().getDevPropertys());
                         binding.recyAddView.setAdapter(addDeciveCustomViewAdapt);
                    }
                }
            }
        });
        viewModel.save.observe(this, new Observer<StateData<Object>>() {
            @Override
            public void onChanged(StateData<Object> objectStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (objectStateData.getStatus()== StateData.DataStatus.SUCCESS){
                    XToast.success(AddDeciveActivity1.this,"保存成功").show();

                    ActivityTool.getInstance().popOneActivity(AddDeciveActivity1.this);
                }else{
                    XToast.error(AddDeciveActivity1.this,"保存失敗").show();
                }
            }
        });
        viewModel.TypeListDatas.observe(this, new Observer<StateData<List<DeviceType>>>() {
            @Override
            public void onChanged(StateData<List<DeviceType>> listStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (listStateData.getStatus() == StateData.DataStatus.SUCCESS) {
                    if (listStateData.getData().size() > 0) {
                        ArrayList<String> list = new ArrayList();
                        hashMapTypeListDatas = new HashMap<>();
                        for (int i = 0; i < listStateData.getData().size(); i++) {
                            list.add(listStateData.getData().get(i).getName());
                            hashMapTypeListDatas.put(listStateData.getData().get(i).getName(), listStateData.getData().get(i).getCode());
                        }
                        int size4 = list.size();
                        String[] array4 = (String[]) list.toArray(new String[size4]);
                        DeciveType(array4);
                    }
                }
            }
        });
        viewModel.DevicePropertys.observe(this, new Observer<StateData<List<DevTypeExtendInfo.DeviceProperty>>>() {
            @Override
            public void onChanged(StateData<List<DevTypeExtendInfo.DeviceProperty>> listStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                if (listStateData.getStatus() == StateData.DataStatus.SUCCESS) {

                    List<String> da=new ArrayList<>();

                    if (adapt == null) {
                        adapt = new QuestListAdapt(R.layout.item_quest_list, da);
                        binding.recyList.setAdapter(adapt);
                    } else {
                        adapt.setNewData(da);
                    }

                    if (listStateData.getData().size() > 0) {
                        List<DevTypeExtendInfo.DeviceProperty> data = listStateData.getData();
                        List<PointInspectDeviceResponse.DeviceProperty> datas=new ArrayList<>();
                        for (DevTypeExtendInfo.DeviceProperty entrty: data) {
                            PointInspectDeviceResponse.DeviceProperty deviceProperty =new PointInspectDeviceResponse.DeviceProperty();
                            deviceProperty.Code=entrty.Code;
                            deviceProperty.Data=entrty.Data;
                            deviceProperty.Index=entrty.Index;
                            deviceProperty.Name=entrty.Name;
                            deviceProperty.Type=entrty.Type;
                            deviceProperty.Value=entrty.Value;
                            datas.add(deviceProperty);
                        }


                        addDeciveCustomViewAdapt =new AddDeciveCustomViewAdapt(R.layout.item_add_decive_custom_view,datas);
                        binding.recyAddView.setAdapter(addDeciveCustomViewAdapt);
                    }}
            }
        });
        viewModel.DeviceQuests.observe(this, new Observer<StateData<List<DevTypeExtendInfo.Questions>>>() {
            @Override
            public void onChanged(StateData<List<DevTypeExtendInfo.Questions>> listStateData) {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
                 if (listStateData.getStatus()== StateData.DataStatus.SUCCESS){
                     if (listStateData.getData().size()>0){
                         ArrayList<String> list = new ArrayList();
                         hashMapQuestTypeDatas = new HashMap<>();
                         hashMapQuestTypeDatas1 = new HashMap<>();
                         for (int i = 0; i < listStateData.getData().size(); i++) {
                             list.add(listStateData.getData().get(i).getQuestsName());
                             hashMapQuestTypeDatas1.put(listStateData.getData().get(i).getQuestsName(),listStateData.getData().get(i).getQuestsCode());
                             hashMapQuestTypeDatas.put(listStateData.getData().get(i).getQuestsName(),listStateData.getData().get(i).getQuesItems());
                         }
                         int size4 = list.size();
                         String[] array4 = (String[]) list.toArray(new String[size4]);
                         QuestType(array4);
                     }
                 }
            }
        });
        viewModel.datas.observe(this, new Observer<StateData<List<String>>>() {
            @Override
            public void onChanged(StateData<List<String>> listStateData) {

                if (adapt == null) {
                    adapt = new QuestListAdapt(R.layout.item_quest_list, listStateData.getData());
                    binding.recyList.setAdapter(adapt);
                } else {
                    adapt.setNewData(listStateData.getData());
                }
            }
        });

    }




    private void DeciveType(final String[] o) {
        mDeciveType = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                binding.edPointType.setText(o[options1]);
                mDeciveTypeOption = options1;
                DevTypeNo = hashMapTypeListDatas.get(o[options1]);
                if (loadingDialog == null) {
                    loadingDialog = new MiniLoadingDialog(AddDeciveActivity1.this, "加載中...");
                }
                loadingDialog.show();
                //请求
                viewModel.GetDevTypeExtendInfo(RouteInspectNo, DevTypeNo);
                return false;
            }


        }).setCancelText("取消")//取消按钮文字
                .setSubmitText("確認")//确认按钮文字
                .setTitleText("請選擇設備類型")
                .setSubCalSize(16)
                .setSubCalSize(16)

                .setSelectOptions(mDeciveTypeOption)
                .build();
        mDeciveType.setPicker(o);

    }




    private void QuestType(final String[] o) {
        mQuestType = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public boolean onOptionsSelect(View view, int options1, int options2, int options3) {
                binding.edPointQuestList.setText(o[options1]);
                mQuestTypeOption = options1;
                //設置問題集數據
                setQuestListData(o[options1]);
                QuestsNo=hashMapQuestTypeDatas1.get(o[options1]);
//                CategoryCode=hashMap.get(o[options1]);
                return false;
            }


        }).setCancelText("取消")//取消按钮文字
                .setSubmitText("確認")//确认按钮文字
                .setTitleText("請選擇問題集")
                .setSubCalSize(16)
                .setSubCalSize(16)

                .setSelectOptions(mQuestTypeOption)
                .build();
        mQuestType.setPicker(o);

    }

    private void setQuestListData(String s) {
        List<DevTypeExtendInfo.Questions.QuestionItem> o = hashMapQuestTypeDatas.get(s);
        if (o!=null&&o.size()>0){
            List<String> da=new ArrayList<>();
            for (int i = 0; i < o.size(); i++) {
                da.add(o.get(i).Name);
            }

            if (adapt == null) {
                adapt = new QuestListAdapt(R.layout.item_quest_list, da);
                binding.recyList.setAdapter(adapt);
            } else {
                adapt.setNewData(da);
            }
        }

    }


}
